 var assignArr =[];//指派人员
 var cur={
		 constant:{
			 user_i:0,
		 }
 }
;$(function () {
    var serverIdArr =[];
    var id = $("#id").val();
    getDeptList();
    if(id==null||id==""){
    	upload(serverIdArr);
    }else{
    	getInfo(id, serverIdArr);
    }
    submitForm();
})
var tale = new $.tale();//弹框
function upload(serverIdArr){
    $("#dropzone").dropzone({
        paramName: "file",
        url: "/file/upload",
        addRemoveLinks: true,
        dictRemoveLinks: "x",
//        uploadMultiple: true,
        maxFilesize: 10,
        init: function () {
            this.on("success", function (file, msg) {
               	file.serverId=msg.message;
               	serverIdArr=msg.message;
            	$("#image_files").val(serverIdArr);
            });
            this.on('error', function (files, response) {
                //文件上传失败后的操作
            	console.log(files, response);
            });
            //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
            this.on("removedfile", function (file) {
            	$("#image_files").val("");
            });
        }
    });
}
function getInfo(id, serverIdArr) {
    $.ajax({
        url: ctxPath+"/supervise/business/findById/" + id,
        type: 'GET',
        success: function (d) {
            var success = d.success;
            if (success == true) {
                var data = d.data;
                umbinding.bind(data);
                if(data.supervisionUserList!=null){
                	to_User_Show(data.supervisionUserList);
                }
                serverIdArr.push(data.fileIds);
                $("#image_files").val(serverIdArr);
                var myDropzone = new Dropzone("#dropzone", {
                    paramName: "file",
                    url: ctxPath+"/file/upload",
                    addRemoveLinks: true,
                    dictRemoveLinks: "x",
//        	        uploadMultiple: true,
                    maxFiles: 3,
                    maxFilesize: 10,
                    init: function () {
                        this.on("success", function (file, msg) {
                            file.serverId = msg.message;
                            serverIdArr.push(msg.message);
                            $("#image_files").val(serverIdArr);
                        });
                        this.on('error', function (files, response) {
                        });
                        //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
                        this.on("removedfile", function (file) {
                            serverIdArr.splice($.inArray(file.serverId, serverIdArr), 1);
                            $("#image_files").val(serverIdArr);
                        });
                    }
                });
                if (data.files != null) {
                    for (var i = 0; i < data.files.length; i++) {
                        var size = data.files[i].size * 1024;
                        var mockFile = {
                            name: data.files[i].srcname,
                            accepted: true,
                            size: size, //图片尺寸
                            height: "70%",
                            width: "70%",
                            type: '.jpg,.png,.gif'//图片文件类型
                        };
                        myDropzone.emit("addedfile", mockFile);
                        myDropzone.emit("thumbnail", mockFile, ctxPath+"/file/showImage/" + data.files[i].id);
                        myDropzone.emit("complete", mockFile);
                    }
                }
            }
        },
        error: function () {
        }

    });
}

function to_User_Show(data){
	var html=[];
	 var img=ctxPath+'/image/defualt.png';
	 
	$.each(data,function(i,item){
		 if(item.headImage!=null){
			 img=ctxPath+'/file/showImage/'+item.headImage;
		 }
	    var div='<div class="col-sm-4" id="supervison_user_'+item.userId+'"><div class="imgContainer"><img title="" alt="" src="'+img+'" style="height: 100px;"><p onclick="removeImg('+item.userId+')" class="imgDelete" >删除</p></div><br>'
		+'<span>'+item.nickname+'</span><input style="display:none;" id="user_'+item.userId+'" value="'+item.userId+'" name="supervisionUserList['+cur.constant.user_i+'].userId">'
		+'<input style="display:none;" id="dept_'+item.userId+'" value="'+item.deptId+'" name="supervisionUserList['+cur.constant.user_i+'].deptId"></div>';
	    html.push(div);
	    cur.constant.user_i=cur.constant.user_i+1;
	    assignArr.push(item.userId);
		$("#assign").val(assignArr);
	})
	$("#userList").append(html);
}

function removeImg(userId){
	 assignArr.splice($.inArray(userId, assignArr), 1);
	 $("#assign").val(assignArr);
	$("#supervison_user_"+userId).remove();
}

function submitForm() {
    $("#global-form").validator({
        rules: {
            mobile: function (element, params) {
                var tel = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
                return tel.test(element.value) || '请检查电话号码';
            },
            username:function(element){
	    		var name = element.name;
	    		var json={};
	    		   json[name] = element.value;
	    		  var value = $("#id").val();
	    		  if(value!=null&&value!=''){
	    			  var id="id";
	    			  json[id] = value;
	    		  }
	    		var isValid = true;
	        	$.ajax({
	        		 url: ctxPath+'/set/admin/checkUsername',
	                 type: 'post',
	                 data: json,
	                 dataType: 'json',
	                 async:false,
	                 success: function(d){
	                	 isValid =  d;
	                 }
	        	})
	        	return isValid|| "帐号重复";
	    	}
        },
        fields: {
            title: {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
            urgencyDegree: {
                rule: "required;checked",
                msg: {
                    required: "必填!"
                }
            },
            'users': {
                rule: "required;",
                msg: {
                    required: "必填!"
                }
            },
            'remark': {
            	rule: "required;",
            	msg: {
            		required: "必填!"
            	}
            },
            'type': {
            	rule: "required;checked",
            	msg: {
            		required: "必填!"
            	}
            },
        },
        invalid: function (form, errors) {
            console.log(errors);
            $(".btn-submit").removeAttr("style");
        },
        //验证成功
        valid: function (form) {
            saveInfo();
        },
    });
}

function saveInfo() {
    var json = $("#global-form").serializeFormJSON();
    console.log(json);
    var id = $("#id").val();
    var url = ctxPath+"/supervise/business/saveInfo";
    if (id != '' && id != null) {
        url = ctxPath+"/supervise/business/updateInfo";
    }
    $.ajax({
        url: url,
        type: 'POST',
        data: json,
        success: function (d) {
            var success = d.success;
            if (success) {
                tale.alertOk({
                    text: '保存成功',
                    then: function () {
                        setTimeout(function () {
                            window.location.href = ctxPath+'/supervise/business/list';
                        }, 500);
                    }
                });
            } else {
                tale.alertError(result.message || '保存失败');
            }
        }
    });
}

/**
 * 获取组织机构
 * @returns
 */
function getDeptList(){
	$.ajax({
        url: "/agency/dept/getAllList",
        type: 'GET',
        success: function(d){
        	var success = d.success;
        	 if(success==true){
        	if(d.data!=null){
        		var result ='<option value="">请选择</option>';
        		var deptId="";
        	$.each(d.data,function(i,item){
//        		if(i==0){
//        			deptId=item.id;
//        		}
        		result+='<option value="'+item.id+'">'+item.name+'</option>';	
        	})
        	$("#dept_select").html(result);
//        	getUserList(deptId);
        	}	 
        	}
        	 
	}
   })
}


/**
 * 获取机构下的人员
 * @returns
 */
function getUserList(deptId){
	var result ='<option value="">请选择</option>';
	if(deptId==null||deptId==''){
		$("#user_select").html(result);
		return;
	}
	$.ajax({
		url: "/agency/user/findByDeptId/"+deptId,
		type: 'GET',
		success: function(d){
			var success = d.success;
			if(success==true){
				if(d.data!=null){
					$.each(d.data,function(i,item){
						result+='<option value="'+item.userId+'">'+item.userName+'</option>';	
					})
					$("#user_select").html(result);
				}	 
			}
			
		}
	})
}

/**
 * 获取人员信息
 * @returns
 */
function getUser(userId){
	if(userId==null||userId==''){
//		$("#userList").html("");
		return;
	}
	$.ajax({
		url: "/user/findById/"+userId,
		type: 'GET',
		success: function(d){
			var success = d.success;
			if(success==true){
				var result="";
				if(d.data!=null){
					 var img='/image/defualt.png';
					 var data =d.data;
					 if(data.headImage!=null){
						 img='/file/showImage/'+data.headImage;	 
					 }
					 var deptId = $("#dept_select").val();
					result+=' <div class="col-sm-3" id="supervison_user_'+data.id+'"><div class="imgContainer"><img title="" alt="" src="'+img+'" style="height: 100px;"><p onclick="removeImg('+data.id+')" class="imgDelete" >删除</p></div><br>'
					+'<span>'+data.nickname+'</span><input style="display:none;" id="user_'+data.id+'" value="'+data.id+'" name="supervisionUserList['+cur.constant.user_i+'].userId">'
					+'<input style="display:none;" id="dept_'+data.id+'" value="'+deptId+'" name="supervisionUserList['+cur.constant.user_i+'].deptId"></div>';	
					var userId= $("#user_"+data.id).val();
					if(userId==null||userId==''){
						assignArr.push(data.id);
						$("#assign").val(assignArr);
						$("#userList").append(result);
						cur.constant.user_i=cur.constant.user_i+1;
					}
				}	 
			}
			
		}
	})
}




